/*
 * 文 件 名:  CustormerReviewsActivity.java
 * 版    权:  Weipu Technologies Co., Ltd. Copyright 2012-2014,  All rights reserved
 * 描    述:  <描述>
 * 修 改 人:  sjx206
 * 修改时间:  2015-1-7
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.epro.dx.activity;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.adapter.ReviewsAdapter;
import com.epro.dx.enable.NetworkBroadcastReceiver;
import com.epro.dx.enable.NetworkBroadcastReceiver.NetWorkCallBack;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.ProductServiceProvider;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.facade.model.ReviewlistModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.Logger;

/**
 * 用户评论
 * 
 * @author sjx206
 * @version [版本号, 2015-1-7]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class ReviewsActivity extends BaseFragmentActivity implements
		NetWorkCallBack {
	/**
	 * 评论接口
	 */

	// 开始位置
	private int pageIndex = 1;

	private PullToRefreshListView listview_layout;

	private ProductModel detailModel;

	private ReviewsAdapter commentListAdapter;

	/**
	 * 评论列表集合
	 */
	private ArrayList<ReviewlistModel> comments = null;

	private ArrayList<ReviewlistModel> onePageReviewList = null;

	private ProductServiceProvider productServiceProvider;

	boolean isLoadContinue = true;

	private ImageButton toTopBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Tracker tracker = DXApplication.getContext().getTracker(
				TrackerName.APP_TRACKER);
		tracker.setScreenName(ReviewsActivity.class.getSimpleName());
		tracker.send(new HitBuilders.ScreenViewBuilder().build());
		// 不显示标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		Intent intent = getIntent();
		if (intent == null) {
			finish();
			return;
		}
		Bundle bundle = intent.getExtras();
		if (null == bundle) {
			finish();
			return;
		}
		detailModel = (ProductModel) bundle.getParcelable("detailModel");
        if(null==detailModel){
        	finish();
			return;
        }
		setContentView(R.layout.activity_custormer_reviews);
		setTitleContent(R.string.title_reviews);
		setLeftBtnContent(true, -1);
		initView();
		setListenner();
		productServiceProvider = ProviderFactory.createProductProvider();
		NetworkBroadcastReceiver.setCallBack(this);
		// showWaitingDialog();
		showLoadingLayout(null);
		// new CommentsListAsyncTask(pageIndex).execute();
		excuteTask(pageIndex);
	}

	/**
	 * 执行加载Comments操作
	 */
	private void excuteTask(int index) {
		AsyncTaskUtil.executeTask(new CommentsListAsyncTask(index));
	}

	private void setListenner() {
		toTopBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if(null!=commentListAdapter){
					commentListAdapter.notifyDataSetInvalidated();
				}
			}
		});
		
		listview_layout
		.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				pageIndex = 1;
				// new CommentsListAsyncTask(pageIndex).execute();
				excuteTask(pageIndex);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// new CommentsListAsyncTask(++pageIndex).execute();
				excuteTask(++pageIndex);
			}
		});
		listview_layout.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int arg1, int arg2, int arg3) {
				if (view.getFirstVisiblePosition() > 4) {
					toTopBtn.setVisibility(View.VISIBLE);
				} else {
					toTopBtn.setVisibility(View.GONE);
				}
				
			}
		});
	}

	/**
	 * 初始化相关
	 */
	private void initView() {
		toTopBtn = (ImageButton) findViewById(R.id.reviewslist_totop);
		listview_layout = (PullToRefreshListView) findViewById(R.id.data_list);
		RatingBar ratingBar = (RatingBar) findViewById(R.id.review_rating);
		ratingBar.setRating(detailModel.getProductRating());
		TextView reviewsCount = (TextView) findViewById(R.id.detail_reviews_count);
		reviewsCount.setText(getString(R.string.detail_reviews_count,
				detailModel.getReviewCount()));
		TextView tvName = (TextView) findViewById(R.id.product_name);
		tvName.setText(detailModel.getShortHeadLine1());
		comments = new ArrayList<ReviewlistModel>();
		commentListAdapter = new ReviewsAdapter(ReviewsActivity.this, comments);
		listview_layout.setAdapter(commentListAdapter);
	}

	@Override
	public void netWorkChangeCallBack(boolean isLoadMore) {
		// 网络由不可用变为可用
		if (isLoadMore) {
			if (null != commentListAdapter) {
				commentListAdapter.notifyDataSetInvalidated();
			}
		}
	}

	/**
	 * 加载商品评论列表任务
	 * 
	 * @author hjd008
	 * @version [版本号, 2014-12-23]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */

	protected class CommentsListAsyncTask extends BaseNeedReLoginTask {
		private int start;

		public CommentsListAsyncTask(int start) {
			this.start = start;
		}

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				onePageReviewList = productServiceProvider
						.getCusotmerReviewList(detailModel.getSku(), "", "",
								start, Constant.LIST_PAGE_COUNT,ActivityUtil.getCustomerToken());
			} catch (DxException e) {
				return e.getErrCode();
			} catch (Exception e) {
				Logger.e("DetailActivity", "CommentsListAsyncTask", e);
			}
			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (!isFinishing()) {
				// hideWaitingDialog();
				hideAllLayout();
				if ("0".equals(result)) {
					if (1 == start) {
						comments.clear();
					}
					if (null == onePageReviewList) {
						listview_layout.onRefreshComplete();
						listview_layout.setMode(Mode.BOTH);
						return;
					}
					if (onePageReviewList.size() < Constant.LIST_PAGE_COUNT) {
						comments.addAll(onePageReviewList);
						commentListAdapter.notifyDataSetChanged();
						listview_layout.onRefreshComplete();
						listview_layout.setMode(Mode.PULL_FROM_START);
					} else {
						comments.addAll(onePageReviewList);
						commentListAdapter.notifyDataSetChanged();
						listview_layout.onRefreshComplete();
						listview_layout.setMode(Mode.BOTH);
					}
				} else if(!isRelogin){
					// 异常问题时问题
					AlertToast.alert(ReviewsActivity.this,
							ServerConstant.ReturnCode.MESSAGEMAP.get(result));
					commentListAdapter.notifyDataSetInvalidated();
					listview_layout.onRefreshComplete();
					listview_layout.setMode(Mode.BOTH);
					pageIndex--;
				}
			}

		}

		@Override
		protected Context setContext() {
			return ReviewsActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new CommentsListAsyncTask(start);
		}
	}

	@Override
	protected void onDestroy() {
		NetworkBroadcastReceiver.setCallBack(null);
		super.onDestroy();
	}
}
